<?php

class User_AuthController extends Zend_Controller_Action
{

	public function init()
	{

	}

	public function resetPasswordAction()
	{
		$table = new User_Model_DbTable_Users();
		$user = $table -> find(1) -> current();
		$user -> setPassword('admin');
		$user -> save();
	}

	public function loginAction()
	{
		// check login mode
		$loginMode = 1;
		
		$form = $this -> view -> form = new User_Form_Login();

		$req = $this -> getRequest();

		if ($req -> isPost() && $form -> isValid($req -> getPost()))
		{
			$values = $form -> getValues();
			// prepare validate
			$adapter = new User_Plugin_Auth_DbTable();
			$adapter -> setIdentity($values['email']);
			$adapter -> setCredential($values['password']);
			$adapter -> setLoginMode($loginMode);

			// check authenticate
			$auth = Zend_Auth::getInstance();
			$result = $auth -> authenticate($adapter);

			// if is valid
			if ($result -> isValid())
			{

				// redirect user.
				$url = Zend_Controller_Front::getInstance() -> getRouter() -> assemble(array(), 'home', true);
				$this -> _helper -> redirector -> setPrependBase(false) -> gotoUrl($url);
				return;
			}
			else
			{
				$code = $result -> getCode();
				switch($code) {
					case User_Plugin_Auth_Result::FAILURE_CREDENTIAL_INVALID :
						echo 'invalid password';
						break;
					case User_Plugin_Auth_Result::FAILURE_UNCATEGORIZED :
						echo 'unknow error';
						break;
					case User_Plugin_Auth_Result::FAILURE_IDENTITY_NOT_FOUND :
						echo 'not match';
						break;
				}
			}
		}
	}

	public function logoutAction()
	{
		$viewer = Nuo::getViewer();
		$auth = Zend_Auth::getInstance();
		$auth -> clearIdentity();
		$url = Zend_Controller_Front::getInstance() -> getRouter() -> assemble(array(), 'home', true);
		$this -> _helper -> redirector -> setPrependBase(false) -> gotoUrl($url);
		return;
	}

}
